package com.alen.sun.controller;

import com.alen.sun.bean.Employee;
import com.alen.sun.bean.PageBean;
import com.alen.sun.bean.Result;
import com.alen.sun.service.ActivityService;
import com.alen.sun.service.EmployeeService;
import com.alen.sun.util.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@CrossOrigin
@RequestMapping("/employees")
@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 添加护工
     * @param employee
     * @return
     */
    @PostMapping()
    public Result addEmployee(@RequestBody Employee employee) {
        Boolean flag=employeeService.add(employee);
        if(flag) {
            //true--注册成功
            return Result.success();
        }else {
            //false--注册失败
            return Result.error("添加错误，请重试");
        }
    }

    /**
     * 修改护工
     * @param employee
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Employee employee){
        Boolean flag=employeeService.update(employee);
        if (flag){
            return Result.success();
        }else {
            return Result.error("抱歉，修改失败");
        }

    }

    /**
     * 获取未分配满4人老人的护工id
     * @return
     */
    @GetMapping("/getEmployeeId")
    public Result getEmployeeId(){
        List<String> employeeIds = employeeService.getEmployeeId();
        return Result.success(employeeIds);
    }

    /**
     * 登录
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Employee employee){
        Employee e=employeeService.login(employee);
        if(e!=null){
            //登录成功，生成令牌，下发令牌
            Map<String,Object> claims=new HashMap<>();
            claims.put("employee",e);
            String jwt= JwtUtils.generateJwt(claims);//jwt包含了当前登录的护工信息
            return Result.success(jwt);
        }else {
            return Result.error("手机号或密码错误");
        }
    }

    /**
     * 通过员工ID获取员工数据
     * @param request
     * @return
     */
    @GetMapping("/token")
    public Result getByToken(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.error("无效的 Token");
        }
        token = token.substring(7);
        // 解析 Token 中的员工 ID
        Employee employee = null;
        try {
            Claims claims = JwtUtils.parseJWT(token);
            employee = new ObjectMapper().convertValue(claims.get("employee"), Employee.class);
            if (employee == null) {
                return Result.error("并未查询到您的数据噢");
            }
        } catch (Exception e) {
            return Result.error("无效的 Token");
        }

        // 根据员工 ID 查询员工数据
        Employee e = employeeService.getById(employee.getEmployeeId());
        if (employee == null) {
            return Result.error("并未查询到您的数据噢");
        }
        // 返回员工数据
        return Result.success(e);
    }

    /**
     * 根据ID删除员工
     * @param id
     * @return
     */
    @DeleteMapping
    public Result delete(@RequestParam String id){
        Boolean flag=employeeService.delete(id);
        if (flag){
            return Result.success();
        }else {
            return Result.error("删除失败");
        }
    }

    /**
     * 护工名字查询
     * @param word
     * @return
     */
    @GetMapping("/search")
    public Result word(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "5") Integer pageSize,
            @RequestParam String word){
        PageBean pageBean = employeeService.page(page,pageSize,word);
        log.info("search被使用");
        return Result.success(pageBean);
    }

    /**
     * 通过ID获取员工信息
     * @return
     */
    @GetMapping("/id")
    public Result getById(@RequestParam String id){
        log.info("根据ID查询员工信息, id: {}",id);
        Employee employee = employeeService.getById(id);
        return Result.success(employee);
    }



    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/ids")
    @ResponseBody
    public Result deleteByIds(@RequestBody List<String> ids) {
        Boolean flag = employeeService.deleteByIds(ids);
        if(flag){
            return Result.success();
        }else {
            return Result.error("批量删除失败");
        }
    }

    @GetMapping("/BI")
    public Result BI(){
        Map<String,Object> BI=new HashMap<>();
        BI = employeeService.BI();
        if (BI!=null){
            return Result.success(BI);
        }else {
            return Result.error("暂未查询到数据");
        }

    }
}
